<!--
 * @Description: 悟空软件
 * @Author: 悟空
 * @LastEditors: yang
-->
<template>
  <wb-section :move="false" class="el-card wb-salary" :showFullIcon="false">
    <flexbox class="body">
      <div class="echart">
        <chartPanel title="人员机构分布">
          <template slot="headerSuffix">
<!--            v-model="sd"-->
            <el-radio-group class="tswitch" :value="totalType" size="small" @input="totalTypeChange">
              <el-radio-button :label="1">人员</el-radio-button>
              <el-radio-button :label="2">机构</el-radio-button>
            </el-radio-group>
          </template>
          <el-radio-group class="tswitch block" :value="statisType" @input="staticsTypeChange">
            <el-radio-button v-for="(item, index) in typeOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
          <div id="deptPie"/>
          <el-button type="primary" icon="el-icon-d-arrow-left" size="small" class="backorg_btn" @click="backOrgHandle"
                     v-if="deepStack.length > 1">
            返回上一级
          </el-button>
        </chartPanel>
        <chartPanel title="从业人员期末人数">
          <div id="workBar"/>
        </chartPanel>
        <chartPanel title="年龄层次">
          <div id="agePie"/>
        </chartPanel>
      </div>
    </flexbox>
  </wb-section>
</template>

<script>
import WbSection from './WbSection'
import WbItem from './WbItem'
import chartPanel from "./chartPanel";
import * as echarts from 'echarts'

export default {
  // 招聘动态
  name: 'WbDeptTotal',
  components: {
    WbSection,
    WbItem,
    chartPanel
  },
  props: {
    deepStack: Array,
    totalData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    orgId: {
      type: String,
      default: "0"
    },
    kind: {
      type: String,
      default: "0"
    },
    query: {
      type: Boolean,
      default: false
    },
    totalType: Number,
    statisType: Number,
    typeOptions: Array
  },
  data() {
    return {
      index: 0,
      workIndex: 0,
      ageIndex: 0,
    }
  },
  computed: {},
  watch: {
    query: {
      handler() {
        this.deptPieInit();
        this.workBarInit();
        this.agePieInit();
      },
    }
  },
  created() {
  },
  mounted() {
    let pMountedTimer = window.setInterval(() => {
      if (window.parentMounted) {
        window.clearInterval(pMountedTimer)
        // 下面就可以写子组件想在mounted时执行代码（此时父组件的mounted已经执行完毕）
        this.deptPieInit();
        this.workBarInit();
        this.agePieInit();
      }
    }, 500)
  },

  beforeDestroy() {
  },
  methods: {
    backOrgHandle() {
      this.$emit('goBackOrg')
    },
    totalTypeChange(value) {
      this.$emit('totalTypeChange', value)
    },
    staticsTypeChange(value) {
      this.$emit('staticsTypeChange', value)
    },
    getValueOrDefault(value, defaultValue) {
      return (value === null || value === undefined || Number.isNaN(value) || value === '') ? defaultValue : value;
    },
    deptPieInit() {
      let userTotal = this.getValueOrDefault(this.totalData.总人数, 0);
      let deptArray = [];
      let numMap = {}
      let originNameMap = {}
      let legendArr = []
      this.totalData.部门人数统计.forEach(dept => {
        let name = dept.name + "(" + this.getValueOrDefault(dept.currentNum, 0) + ")"
        let num = this.getValueOrDefault(dept.currentNum, 0)
        let percent = userTotal === 0 ? "0%" : parseFloat(((num / userTotal) * 100).toFixed(2)) + '%'
        numMap[name] = percent
        originNameMap[name] = dept.name
        deptArray.push({
          value: this.getValueOrDefault(dept.currentNum, 0),
          name: name,
          kind: dept.kind,
          orgId: dept.deptId,
        });
        legendArr.push({
          name: name,
          icon: dept.deptType == '2' ? 'circle' : 'rect',
        })
      })
      var myChart = echarts.init(document.getElementById('deptPie'))
      var option = {
        title: {
          text: userTotal,
          show: false,
          subtext: this.totalType == 1 ? '员工总数' : '机构总数',
          left: '30%',
          top: '45%',
          textStyle: {
            fontSize: '36px',
            color: '#1C70E3',
            align: 'center'
          },
          subtextStyle: {
            fontSize: '18px',
            color: '#545454'
          }
        },
        tooltip: {
          trigger: 'item',
          // formatter: "{a} <br/>{b}: {c} ({d}%)"
          formatter: "{b}: {c} ({d}%)"
        },
        legend: {
          right: 'right',
          top: "center",
          icon: 'circle',
          type: 'scroll',
          orient: 'vertical',
          itemWidth: 15,
          data: legendArr,
          formatter: function (name) {
            let originName = originNameMap[name]
            let percent = numMap[name]
            return `${originName} \t ${percent}`;
          }
        },
        series: [
          {
            name: '总人数',
            type: 'pie',
            radius: ['35%', '60%'],
            center: ['40%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              color: '#4c4a4a',
              formatter: `{total|${userTotal}}\n\r{active|${this.totalType == 1 ? '员工总数' : '机构总数'}}`,
              rich: {
                total: {
                  fontSize: '36px',
                  color: '#1C70E3',
                  fontFamily: '微软雅黑'
                },
                active: {
                  fontSize: '18px',
                  color: '#545454',
                  fontFamily: '微软雅黑'
                }
              },
              emphasis: {
                show: true,
              }
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 10,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              normal: {show: false},
              emphasis: {show: true},
              tooltip: { show: false}
            },
            data: deptArray
          }
        ]
      };
      myChart.setOption(option);
      if (this.index == 0) {
        //图例点击事件
        myChart.on('legendselectchanged', (params) => {
          var node = myChart.getOption().series[0].data.find(item => item.name === params.name);
          this.$emit('click-legend', node)
          //将默认点击事件中取消选中的legend动态设置回来
          myChart.setOption({
            legend: {selected: {[params.name]: true}}
          })
        })
        this.index++;
      }
    },
    workBarInit() {
      let postData = this.totalData.从业人员;
      var myChart = echarts.init(document.getElementById('workBar'))

      // var option = {
      //   // title: {
      //     // text: '人员结构-从业人员期末人数',
      //     // left: 'center'
      //   // },
      //   tooltip: {
      //     trigger: 'axis',
      //     formatter: function (params) {
      //       var result = params[0].name + '<br/>';
      //       params.forEach(function (item) {
      //         if (item.value >= 0) {
      //           result += item.seriesName + ': ' + item.value + '<br/>';
      //         }
      //       });
      //       return result;
      //     },
      //     axisPointer: {
      //       type: 'shadow'
      //     }
      //   },
      //   legend: {
      //     bottom: '5%',
      //     left: '12%',
      //     right: '12%',
      //     type: 'scroll',
      //     icon: 'rect',
      //   },
      //   grid: {
      //     top: '5%',
      //     left: '3%',
      //     right: '4%',
      //     bottom: '13%',
      //     containLabel: true
      //   },
      //   xAxis: {
      //     type: 'value'
      //   },
      //   yAxis: {
      //     type: 'category',
      //     data: ['劳动合同工', '劳务', '临时工', '其他']
      //   },
      //   series: [
      //     {
      //       name: '劳动合同工',
      //       type: 'bar',
      //       stack: 'total',
      //       barWidth: '16px',
      //       label: {
      //         show: true
      //       },
      //       emphasis: {
      //         focus: 'series'
      //       },
      //       data: [this.getValueOrDefault(postData.劳动合同工, 0)]
      //     },
      //     {
      //       name: '劳务外包',
      //       type: 'bar',
      //       stack: 'total',
      //       barWidth: '16px',
      //       label: {
      //         show: true
      //       },
      //       emphasis: {
      //         focus: 'series'
      //       },
      //       data: ['-', this.getValueOrDefault(postData.劳务外包, 0)]
      //     },
      //     {
      //       name: '临时工',
      //       type: 'bar',
      //       stack: 'total',
      //       barWidth: '16px',
      //       label: {
      //         show: true
      //       },
      //       emphasis: {
      //         focus: 'series'
      //       },
      //       data: ['-', '-', this.getValueOrDefault(postData.临时工, 0)]
      //     },
      //     {
      //       name: '劳务派遣',
      //       type: 'bar',
      //       stack: 'total',
      //       barWidth: '16px',
      //       label: {
      //         show: true,
      //       },
      //       emphasis: {
      //         focus: 'series'
      //       },
      //       data: ['-', this.getValueOrDefault(postData.劳务派遣, 0)]
      //     },{
      //       name: '退休返聘',
      //       type: 'bar',
      //       stack: 'total',
      //       barWidth: '16px',
      //       label: {
      //         show: true,
      //       },
      //       emphasis: {
      //         focus: 'series'
      //       },
      //       data: ['-', '-', '-', this.getValueOrDefault(postData.退休返聘, 0)]
      //     },
      //     {
      //       name: '外部董事',
      //       type: 'bar',
      //       stack: 'total',
      //       barWidth: '16px',
      //       label: {
      //         show: true,
      //       },
      //       emphasis: {
      //         focus: 'series'
      //       },
      //       data: ['-', '-', '-', this.getValueOrDefault(postData.外部董事, 0)]
      //     },
      //   ]
      // };
      const other = this.getValueOrDefault(postData.退休返聘, 0) + this.getValueOrDefault(postData.外部董事, 0)
      const xdata = [
        { value: this.getValueOrDefault(postData.劳动合同工, 0), name: '劳动合同工', itemStyle: { color: '#5F4BF3'}},
        { value: this.getValueOrDefault(postData.劳务派遣, 0), name: '劳务派遣', itemStyle: { color: '#1284F4'} },
        { value: this.getValueOrDefault(postData.劳务外包, 0), name: '劳务外包', itemStyle: { color: '#00BFE9'} },
        { value: this.getValueOrDefault(postData.临时工, 0), name: '临时工', itemStyle: { color: '#FFC834'} },
        { value: other, name: '其他', itemStyle: { color: '#F16261'} }
      ]
      let total = xdata.reduce((a, b) => a + b.value, 0)
      var option = {
        tooltip: {
          trigger: 'item'
        },
        title: {
          text: `从业人员\n占比分析\n\n${total}`,
          left: 'center',
          top: '30%',
          textStyle: {
            fontSize: 28
          }
        },
        legend: {
          bottom: '5%',
          left: 'center'
        },
        graphic: [{
          type: 'group',
          top: '0%',
          right: '0%',
          children: [{
            type: 'rect',
            shape: {
              width: 150,
              height: 70
            },
            style: {
              fill: '#f8f9fa',
              stroke: '#e9ecef',
              lineWidth: 1
            }
          }, {
            type: 'text',
            left: 10,
            top: 10,
            style: {
              fill: '#495057',
              text: `外部董事: ${this.getValueOrDefault(postData.外部董事, 0)}人\n退休返聘: ${this.getValueOrDefault(postData.退休返聘, 0)}人`,
              font: '14px Microsoft YaHei',
              lineHeight: 25
            }
          }]
        }],
        series: [
          {
            "name": "",
            "type": "gauge",
            "center": ['50%', '45%'], // 修改垂直位置
            "radius": "60%",
            "min": 0,
            "max": 100,
            "splitNumber": 10,
            "startAngle": 180,
            "endAngle": 360,
            "axisLine": {
              "roundCap": true,
              "lineStyle": {
                "width": 0,
                "opacity": 0,
                "color": [
                  [
                    0.19,
                    "#d9d9d9"
                  ],
                  [
                    1,
                    "#d9d9d9"
                  ]
                ]
              }
            },
            "axisLabel": {
              "show": false
            },
            "axisTick": {
              "show": true,
              "splitNumber": 7,
              "lineStyle": {
                "color": "auto",
                "width": 2
              },
              "length": 16
            },
            "splitLine": {
              "show": false,
              "length": 20,
              "distance": 9,
              "lineStyle": {
                "color": "auto",
                "width": 3
              }
            },
            "detail": {
              "show": false
            },
            "pointer": {
              "show": false
            }
          },
          {
            name: '从业人员占比分析',
            type: 'pie',
            radius: ['65%', '85%'],
            center: ['50%', '45%'], // 同样修改垂直位置
            startAngle: 180,
            endAngle: 360,
            itemStyle: {
              borderRadius: 0,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
            },
            data: xdata
          }
        ]
      }
      myChart.setOption(option);
      if (this.workIndex == 0) {
        //图例点击事件
        myChart.on('legendselectchanged', (params) => {
          // var node = myChart.getOption().series.find(item => item.name === params.name);
          this.$emit('click-work', params)
          //将默认点击事件中取消选中的legend动态设置回来
          myChart.setOption({
            legend: {selected: {[params.name]: true}}
          })
        })
        this.workIndex++;
      }
    },
    agePieInit() {
      let ageData = this.totalData.年龄结构;
      var myChart = echarts.init(document.getElementById('agePie'))
      let chartData = [
        {value: this.getValueOrDefault(ageData['35以下'], 0), name: '≤35'},
        {value: this.getValueOrDefault(ageData['36-40'], 0), name: '36-40'},
        {value: this.getValueOrDefault(ageData['41-45'], 0), name: '41-45'},
        {value: this.getValueOrDefault(ageData['46-50'], 0), name: '46-50'},
        {value: this.getValueOrDefault(ageData['51-55'], 0), name: '51-55'},
        {value: this.getValueOrDefault(ageData['55以上'], 0), name: '>55'},
      ]
      let sum = chartData.reduce((sum, current) => {
        return sum + Number(current.value || 0)
      }, 0)
      const nameNumMap = chartData.reduce((map, current) => {
        const percent = parseFloat(((current.value / sum) * 100).toFixed(2)) + '%'
        map[current.name] = percent
        return map
      }, {})

      var option = {
        // title: {
        //   text: '人员结构-年龄层次',
        //   left: 'center'
        // },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          right: 'right',
          top: "center",
          icon: 'circle',
          formatter: function (name) {
            return `${name} \t ${nameNumMap[name]}`;
          }
        },
        // 右上角工具栏
        // toolbox: {
        //   show: true,
        //   feature: {
        //     mark: {show: true},
        //     dataView: {show: true, readOnly: false},
        //     restore: {show: true},
        //     saveAsImage: {show: true}
        //   }
        // },
        series: [
          {
            name: '年龄占比',
            type: 'pie',
            // radius: '60%',
            roseType: 'area',
            radius: ['10%', '70%'],
            center: ['40%', '50%'],
            padAngle: 2,
            itemStyle: {
              borderRadius: 5
            },
            label: {
              show: true,
              formatter: (params) => {
                if (params) {
                  return params.value //`${params.name}` + '\t ' + `${params.percent === undefined ? 0 : params.percent || 0}%`
                }
                return ''
              },
            },
            data: chartData
          }
        ]
      };
      myChart.setOption(option);
      if (this.ageIndex == 0) {
        //图例点击事件
        myChart.on('legendselectchanged', (params) => {
          var node = myChart.getOption().series[0].data.find(item => item.name === params.name);
          this.$emit('click-age', node)
          //将默认点击事件中取消选中的legend动态设置回来
          myChart.setOption({
            legend: {selected: {[params.name]: true}}
          })
        })
        this.ageIndex++;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wb-salary {
  &.card{
    box-shadow: none;
    padding: 0;
    &::before{
      height: 0;
    }
  }
  .body {
    padding: 15px 0;
  }

  .wb-item {
    flex: 1;
    flex-shrink: 0;
  }

  .echart {
    position: relative;
    flex: 1;
    display: flex;
    justify-content: center;
    column-gap: 20px;
    #deptPie {
      width: 100%;
      height: 446px;
      margin: 0 auto;
    }

    #workBar {
      width: 100%;
      height: 500px;
      margin: 0 auto;
    }

    #agePie {
      width: 100%;
      height: 500px;
      margin: 0 auto;
    }

    .empty-text {
      position: absolute;
      top: 50%;
      left: 50%;
      z-index: 0;
      color: $--color-text-secondary;
      transform: translate(-50%, -50%);
    }
  }
}
.tswitch{
  border-radius: 50px;
  background-color: #F8FAFE;
  ::v-deep .el-radio-button__inner{
    border-radius: 50px;
    background-color: #F8FAFE;
    border: none;
    min-width: 48px;
    min-height: 22px;
    line-height: 22px;
  }
  ::v-deep .is-active .el-radio-button__inner{
    background: linear-gradient( 311deg, #1C70E3 0%, #6BAAFF 100%);
  }
  &.block{
    width: 100%;
    margin-top: 16px;
    display: flex;
    ::v-deep .el-radio-button{
      flex: 1;
    }
    ::v-deep .el-radio-button__inner{
      width: 100%;
    }
  }
}
.backorg_btn{
  position: absolute;
  right: 14px;
  top: 50px
}
</style>
